
import cv2
import os
import cv2
import skimage.io
import skimage.filters
import pandas as pd
# from skimage import median
from skimage import exposure
from skimage.morphology import disk
from skimage.feature import (greycomatrix, greycoprops)
import numpy as np
from skimage import exposure


def preProcess(path, gap, pic_start, pic_end, gray_type, path_save,gauss_para, median_para,):

    print(path)
    print(gap)
    print(pic_start)
    print(pic_end)
    print(gray_type)
    print(path_save)

    for i in range(pic_start, pic_end + 1, gap):
        mixPath = path + '/picture-' + str(i) + '.jpg'
        # 分为灰度图和原图的读取 cv的imread第二个参数为0为灰度图 1为原RGB图
        # img = cv2.imread(mixPath, 0)
        # skimage.io.imread读取第二个参数True为灰度图 False为RGB原图
        # imgx = skimage.io.imread(mixPath, True)
        imgx = cv2.imread(mixPath, 0)
        # rea = skimage.io.imread(path, False)
        # 对比度有限自适应直方图均衡化（CLAHE）
        if gray_type == 0:
            imgx = exposure.equalize_adapthist(imgx, kernel_size=None, clip_limit=0.01, nbins=256)

        if gray_type == 1:
            # imgx = skimage.io.imread(mixPath, True)
            imgx = cv2.imread(mixPath, 0)


        # 图片保存到相应路径
        gs = skimage.filters.gaussian(imgx, sigma=gauss_para)
        # 复制一张原图用来标识画出选框
        mark = imgx.copy()
        # 灰度图减去光背景图 可视作留下的就是絮体
        img1 = imgx - gs
        # skimage.img_as_ubyte（image，force_copy）将图像转换为8位无符号整数格式。
        img1 = skimage.img_as_ubyte(img1, force_copy=False)
        ret2, th2 = cv2.threshold(img1, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
        # 二值图中值滤波

        res = skimage.filters.median(th2, disk(median_para))
        # las = cv2.erode(res, disk(median_para))
        last = cv2.dilate(res, disk(median_para))
        SavePath = path_save + '/gray-' + str(i) + '.png'
        # img = np.array(imgx, dtype=np.uint8)
        # skimage.io.imsave(SavePath, imgx)

        cv2.imwrite(SavePath, last)
    print('image ok!')